/*
 * Copyright (c) Kumo Inc. and affiliates.
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

#include <melon/io/io_buf.h>
#include <melon/io/async/async_transport.h>
#include <melon/io/async/decorated_async_transport_wrapper.h>

namespace melon {

/**
 * Helper class that redirects write() and writev() calls to writeChain().
 */
template <class T>
class WriteChainAsyncTransportWrapper
    : public DecoratedAsyncTransportWrapper<T> {
 public:
  using DecoratedAsyncTransportWrapper<T>::DecoratedAsyncTransportWrapper;

  void write(
      AsyncTransport::WriteCallback* callback,
      const void* buf,
      size_t bytes,
      melon::WriteFlags flags = melon::WriteFlags::NONE) override {
    auto ioBuf = melon::IOBuf::wrapBuffer(buf, bytes);
    writeChain(callback, std::move(ioBuf), flags);
  }

  void writev(
      AsyncTransport::WriteCallback* callback,
      const iovec* vec,
      size_t count,
      melon::WriteFlags flags = melon::WriteFlags::NONE) override {
    auto writeBuffer = melon::IOBuf::wrapIov(vec, count);
    writeChain(callback, std::move(writeBuffer), flags);
  }

  /**
   * It only makes sense to use this class if you override writeChain, so force
   * derived classes to do that.
   */
  void writeChain(
      AsyncTransport::WriteCallback* callback,
      std::unique_ptr<melon::IOBuf>&& buf,
      melon::WriteFlags flags = melon::WriteFlags::NONE) override = 0;
};

} // namespace melon
